package com.knife.easyexcel.read.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 *
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2022年02月17日 星期四 4:39 下午
 * @description
 * @since 1.0
 */
public class KnifeUploadExcelReadListener<T> implements ReadListener<T> {

    private final Integer maxListSize;
    private final Consumer<List<T>> consumer;
    private volatile List<T> tempList;

    public KnifeUploadExcelReadListener(Integer maxListSize, Consumer<List<T>> consumer) {
        this.maxListSize = maxListSize;
        this.consumer = consumer;
        this.tempList = new ArrayList<>(maxListSize);
    }


    @Override
    public void invoke(T data, AnalysisContext context) {
        tempList.add(data);
        // 达到指定长度，回收tempList
        if (tempList.size() == maxListSize) {
            consumer.accept(tempList);
            tempList = new ArrayList<>(maxListSize);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!tempList.isEmpty()) {
            consumer.accept(tempList);
            // 回收tempList
            tempList = new ArrayList<>(maxListSize);
        }
    }
}
